
import React from 'react';
import { inject, observer } from 'mobx-react';
import { observable, action, toJS } from 'mobx';
//import { bindActionCreators } from 'redux'
import { WeaTab } from 'ecCom';
import { routerShape } from 'react-router';
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import * as ReportUtil from '../util/report';
import { WeaForm, WeaTableNew, WeaSwitch } from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import {
  WeaTop,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaSearchGroup,
  WeaRightMenu,
  WeaPopoverHrm,
  WeaFormItem,
  WeaNewScroll,
  WeaEchart,
  WeaRadioGroup,
  WeaAlertPage,
} from 'ecCom'

import { WeaErrorPage, WeaTools } from 'ecCom'
import { Button, Form } from 'antd'
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const createForm = Form.create;
const FormItem = Form.Item;
let _this = null;
@inject('meetingReport')
@observer
class RoomUsedReport extends React.Component {
  static contextTypes = {
    router: routerShape
  }
  constructor(props) {
    super(props);
    _this = this;
    this.state = {
      // RoomPlanContainer: false,
      // dialogType: 'preview',
      // meetingId: '',
      viewType: 'chart',
    }

  }
  componentDidMount() {//一些初始化请求
    const { meetingReport } = this.props;
    meetingReport.init();

    if (this.refs.chartpie) {
      this.refs.chartpie.paint();
    }

  }

  componentWillUnmount() {
    //组件卸载时一般清理一些状态
  }
  componentDidUpdate() {
    if (this.refs.chartpie) {
      this.refs.chartpie.paint();
    }
  }

  render() {
    $(window).resize(() => {
      this.refs.chartpie && this.refs.chartpie.chart.resize();
    })
    const { viewType } = this.state;
    const { meetingReport } = this.props;
    let { roomUsed, dataKey, conditioninfo, conditionUsed, condition, roomUsedData, getRoomUsedTableData } = meetingReport;
    let datas = roomUsed.datas;
    let names = [];
    if (datas) {
      datas.forEach((item) => {
        names.push(item.name);
      })
    }
    datas = toJS(datas) || [];
    names = toJS(names) || [];
    conditionUsed = toJS(conditionUsed) || [];
    let datasLen = datas.length;
    let colors = WeaEchart.colors;
    let option = {
      // title: {
      //   text: getLabel(32526, "会议室使用次数统计"),
      //   textStyle: {
      //     lineHeight: 50,
      //     height: 50,
      //     background: '#f8f8f8',
      //     paddingLeft: 16,
      //     marginBottom: 10,
      //     fontSize: 12,
      //     color: '#000',
      //   }
      // },
      tooltip: {
        trigger: 'item',
        formatter: '{b} <br/> {c} ({d}%)'
      },
      legend: {
        bottom: 10,
        data: names,
        type: 'scroll',
        orient: 'vertical',
        left: 20,
        top: 0,
      },
      series: [
        {
          name: getLabel(31232, "会议室名称"),
          type: 'pie',
          radius: '50%',
          center: ['60%', '45%'],
          data: datas,
          itemStyle: {
            normal: {
              color: params => {
                colors.length < datasLen && (colors = colors.concat(colors));
                return colors[params.dataIndex];
              }
            }
          }
        }
      ],
      // toolbox: {
      //   feature: {
      //     saveAsImage: {
      //       type: 'png',
      //       name: 'reportForRoom',
      //       show: true,
      //     }
      //   }
      // }
    }
    return (
      <div className='room-use-report'>
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@l9anih`}
          datas={this.getRightMenu()}
          collectParams={{
            favname: getLabel(32526, "会议室使用次数统计"),
            favouritetype: 5,
            objid: 0,
            importantlevel: 1,
          }}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@9k30iz`}
            title={getLabel(32526, "会议室使用次数统计")}
            loading={true}
            icon={<i className='icon-coms-meeting' />}
            iconBgcolor='#f14a2d'
            buttons={this.getButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={{
              collectParams: {
                favname: getLabel(32526, "会议室使用次数统计"),
                favouritetype: 5,
                objid: 0,
                importantlevel: 1,
              }
            }}>
            {/* <WeaTab
              searchType={['advanced']}
              showSearchAd={meetingReport.ifShowSearchAd}
              //这里接收的是切换显隐之后相应的bool值
              setShowSearchAd={bool => {
                meetingReport.setShowSearchAd(bool)
              }}
              searchsBaseValue={''}
              searchsAd={this.getSearchs()}
              buttonsAd={this.getTabButtonsAd()}
              onSearch={v => {
                this.advancedSearch()
              }}
              onSearchChange={v => { }}
            /> */}
            <div className='room-report-con' id='room-report-con'>
              <div className='room-report-condition'>
                <WeaRadioGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaRadioGroup@nzw1gy`}
                  config={toJS(condition)}
                  onChange={datas => {
                    let bool = true;
                    let timeSag = datas.timeSag, beginDate = datas.beginDate, endDate = datas.endDate, selectType = datas.selectType, subid = datas.subid;
                    if (timeSag && timeSag === '6' && (!beginDate || beginDate === '' || !endDate || endDate === '')) bool = false;
                    if (selectType && selectType === '1' && (!subid || subid === '')) bool = false;
                    if (bool) {
                      roomUsedData(datas);
                      getRoomUsedTableData(datas);
                    }
                  }}
                  beforeInit={
                    (a, b, c) => {
                      c(b);
                    }
                  } />
              </div>
              <div className='room-report-echarts'>
                {
                  this.state.viewType == 'chart' ? (<div>
                    <div className='room-report-echarts-title'>
                      {getLabel(32526, "会议室使用次数统计")}
                      {!isEmpty(option.legend.data)&&(<i className='icon-coms-download2' onClick={this.downloadImg}/>)}
                    </div>
                    <div className='room-report-charts' style={{ height: 600, backgroundColor: '#ffffff', paddingTop: '40px' }}>
                      {
                        isEmpty(option.legend.data) ? (
                          <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@y76m2r`} icon="icon-coms-blank">
                            <div>{getLabel(83553, "暂无数据")}</div>
                          </WeaAlertPage>
                        ):(<WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@i9frrj`} ref="chartpie" option={option} useDefault={false} />)
                      }
                    </div>
                  </div>) : (
                      <div>
                        {meetingReport.tableStore[dataKey] ? <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@fhbd9l`}
                          hasOrder={true}
                          needScroll={false}
                          sessionkey={dataKey}
                          comsWeaTableStore={meetingReport.tableStore[dataKey]}
                        /> : ''}
                      </div>
                    )
                }
              </div>
            </div>
          </WeaTop>
        </WeaRightMenu>

      </div>
    )
  }

  downloadImg = ()=>{
    let echartid  =this.refs.chartpie.chart.id;
    let name=getLabel(32526, "会议室使用次数统计");
    if(echartid!=''){
      const cvs = jQuery("div[_echarts_instance_='"+echartid+"'] canvas")[0];
      ReportUtil.downloadCvs2Img(cvs,name);
    }
  }


  getButtons() {
    const { exportRoomUsedExcel } = this.props.meetingReport;
    let btns = [(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6kcxfz@viewType_list`} type="primary" onClick={() => { this.changeViewType() }}>{getLabel(82532, "列表视图")}</Button>)];
    if (this.state.viewType == 'table') {
      btns = [(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pv1lxe@viewType_chart`} type="primary" onClick={() => { this.changeViewType() }}>{getLabel(82509, "图表视图")}</Button>)];
    }
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7oaqlz@exportAll`} type="primary" onClick={exportRoomUsedExcel}>{getLabel(383381, "导出清单到Excel")}</Button>)
    return btns
  }

  // getTabButtonsAd() {
  //   const { meetingReport } = this.props;
  //   return [
  //     (<Button type="primary"
  //       onClick={() => {
  //         meetingReport.roomUsedData(meetingReport.adSearchForm.getFormParams());
  //         meetingReport.getRoomUsedTableData(meetingReport.adSearchForm.getFormParams());
  //         meetingReport.setShowSearchAd(false);
  //       }}
  //     >
  //       搜索
  //           </Button>),
  //     (<Button type="ghost" onClick={() => { meetingReport.adSearchForm.reset() }}>重置</Button>),
  //     (<Button type="ghost" onClick={() => { meetingReport.setShowSearchAd(false) }}>取消</Button>)
  //   ]
  // }

  //右键菜单
  getRightMenu() {
    let btns = [];
    btns.push({
      key: 'exportToExcel',
      icon: <i className='icon-coms-download2' />,
      content: getLabel(383381, "导出清单到Excel"),
      onClick: this.exportToExcel,
    });
    return btns
  }


  // //高级搜索group定义
  // getSearchs() {
  //   const { meetingReport } = this.props;
  //   const conditioninfo = toJS(meetingReport.conditioninfo);
  //   const { adSearchForm } = meetingReport;
  //   const { isFormInit } = adSearchForm;
  //   let group = [];
  //   isFormInit && conditioninfo.map(c => {
  //     let items = [];
  //     c.items.map(fields => {
  //       items.push({
  //         com: (<WeaFormItem
  //           label={`${fields.label}`}
  //           labelCol={{ span: `${fields.labelcol}` }}
  //           wrapperCol={{ span: `${fields.fieldcol}` }}>
  //           <WeaSwitch fieldConfig={fields} form={adSearchForm} onChange={null/*todo*/} />
  //         </WeaFormItem>),
  //         colSpan: 1
  //       })
  //     });
  //     group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />)
  //   });
  //   return group;
  // }

  changeViewType() {
    const { meetingReport } = this.props;
    if (this.state.viewType == 'chart') {
      // meetingReport.getRoomUsedTableData(meetingReport.adSearchForm.getFormParams());
      this.setState({ viewType: 'table' });
    } else {
      this.setState({ viewType: 'chart' });
    }
  }

  // advancedSearch() {
  //   const { meetingReport } = this.props;
  //   meetingReport.roomUsedData(meetingReport.adSearchForm.getFormParams());
  //   meetingReport.getRoomUsedTableData(meetingReport.adSearchForm.getFormParams());
  // }

}



//组件检错机制
class MyErrorHandler extends React.Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== "";
    return (
      <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@a8yzw7`} msg={hasErrorMsg ? this.props.error : getLabel(383324, "对不起，该页面异常，请联系管理员")} />
    );
  }
}

RoomUsedReport = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(RoomUsedReport);

export default RoomUsedReport
